<?php

namespace app\admin\controller\shopro\order;

use think\Db;
use think\Config;
use app\common\controller\Backend;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\shopro\order\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

        // 手动加载 order_item 语言包
        $this->loadlang('shopro/order/order_item');

        $this->model = new \app\admin\model\shopro\order\Order;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("platformList", $this->model->getPlatformList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','type','order_sn','item','user_id','phone','consignee','province_name','city_name','area_name','address','status','memo','total_amount','total_fee','createtime']);
                $row->item = \app\admin\model\shopro\order\OrderItem::all(['order_id' => $row->id]);
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function detail($id)
    {

        $row = $this->model->get($id);
        $row->user = \app\admin\model\User::get($row->user_id);
        $list = \app\admin\model\shopro\order\OrderItem::where(['order_id' => $id])->select();
//        halt($list);
        $this->assignconfig('order', $row);
        $this->assignconfig('item', $list);
        return $this->view->fetch();

    }



    public function send($id, $item_id = 0) {
        if ($this->request->isAjax()){
            $express_name = $this->request->post('express_name');
            $express_no = $this->request->post('express_no');

            $order = $this->model->where('status', \app\admin\model\shopro\order\Order::STATUS_PAYED)
                                    ->where('id', $id)->find();

            if (!$order) {
                $this->error('订单不存在或未支付');
            }

            $where = ['order_id' => $id];
            if ($item_id) {
                $where['id'] = $item_id;
                $where['dispatch_status'] = \app\admin\model\shopro\order\OrderItem::DISPATCH_STATUS_NOSEND;
            }

            $item_list = \app\admin\model\shopro\order\OrderItem::where($where)->select();

            if (!$item_list) {
                $this->error('没有要发货的订单商品');
            }

            Db::transaction(function () use ($order, $item_list, $express_name, $express_no) {
                foreach ($item_list as $key => $item) {
                    $item->express_name = $express_name;
                    $item->express_no = $express_no;
                    $item->dispatch_status = \app\admin\model\shopro\order\OrderItem::DISPATCH_STATUS_SENDED;    // 已发货状态
                    $item->save();

                    \addons\shopro\model\OrderAction::operAdd($order, $item, $this->auth->getUserInfo(), 'admin', '管理员发货订单');
                }
            });

            $item_list = \app\admin\model\shopro\order\OrderItem::where(['order_id' => $id])->select();
            return $this->success('操作成功', null, $item_list);
        }
    }


    public function aftersaleFinish($id, $item_id) {
        if ($this->request->isAjax()) {
            
            $where = [
                'order_id' => $id,
                'id' => $item_id,
                'aftersale_status' => \app\admin\model\shopro\order\OrderItem::AFTERSALE_STATUS_AFTERING
            ];
            
            $order = $this->model->where('status', 'in', [
                                            \app\admin\model\shopro\order\Order::STATUS_PAYED,
                                            \app\admin\model\shopro\order\Order::STATUS_FINISH
                                        ]
                                    )
                                    ->where('id', $id)->find();
            $item = \app\admin\model\shopro\order\OrderItem::where($where)->find();

            if (!$order || !$item) {
                $this->error('订单不存在或不是售后订单');
            }

            Db::transaction(function () use ($order, $item) {
                $item->aftersale_status = \app\admin\model\shopro\order\OrderItem::AFTERSALE_STATUS_OK;    // 售后完成
                $item->save();

                \addons\shopro\model\OrderAction::operAdd($order, $item, $this->auth->getUserInfo(), 'admin', '管理员售后完成订单');
            });

            $item_list = \app\admin\model\shopro\order\OrderItem::where(['order_id' => $id])->select();
            return $this->success('操作成功', null, $item_list);
        }
    }


    public function refund($id = 0, $item_id = 0)
    {
        if ($this->request->isAjax()) {
            $refund_money = $this->request->post('refund_money');

            $where = [
                'order_id' => $id,
                'id' => $item_id,
                'refund_status' => \app\admin\model\shopro\order\OrderItem::REFUND_STATUS_ING
            ];

            $order = $this->model->where('status', 'in', [
                                            \app\admin\model\shopro\order\Order::STATUS_PAYED, 
                                            \app\admin\model\shopro\order\Order::STATUS_FINISH
                                        ]
                                    )
                                    ->where('id', $id)->find();
            $item = \app\admin\model\shopro\order\OrderItem::where($where)->find();

            if (!$order || !$item) {
                $this->error('订单不存在或不是退款订单');
            }

            // 如果退款金额大于订单支付总金额
            if ($refund_money > $order->total_fee) {
                $this->error('退款金额不能大于实际支付金额');
            }

            Db::transaction(function () use ($order, $item, $refund_money) {
                $item->refund_status = \app\admin\model\shopro\order\OrderItem::REFUND_STATUS_OK;    // 同意退款
                $item->refund_fee = $refund_money;
                $item->save();
 
                \addons\shopro\model\OrderAction::operAdd($order, $item, $this->auth->getUserInfo(), 'admin', '管理员同意订单退款，退款金额：' . $refund_money);

                \app\admin\model\shopro\order\Order::refund($order, $item, $refund_money);
            });

            $item_list = \app\admin\model\shopro\order\OrderItem::where(['order_id' => $id])->select();
            return $this->success('操作成功', null, $item_list);
        }
    }



    public function editMemo($id)
    {
        if ($this->request->isAjax()) {
            $memo = $this->request->post('memo');

            $order = $this->model->get($id);
            if (!$order) {
                $this->error('订单不存在');
            }

            $order->memo = $memo;
            $order->save();

            return $this->success('操作成功', null, $order);
        }
    }
}
